package com.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;


import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

/**
 * Created by chengjun on 2015/1/21.
 */
public class Pic2Util {
	public static String bucketName = "temp";

	public static final String QINIU_DIR = "http://file.changshuclub.com/";

	private static final String ACCESS_KEY = "7wgUBcOq8TzRPoG51xGplyVLObUEEXAb-VwXWMkd";
	private static final String SECRET_KEY = "Qm27gJRBBgnDbENWZmtdKEBV-TERESTaJhviRxwv";

	// 密钥配置
	private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

	// 创建上传对象
    static Configuration c = new Configuration(Zone.autoZone());

    //创建上传对象
    UploadManager uploadManager = new UploadManager(c);

	public static void fops(String key){
		  String mp3 = key.replace(".amr", ".mp3");
		  mp3 = mp3.replace(".wav", ".mp3");
		  try {
			  new BucketManager(auth, c).stat(bucketName, mp3);
		  } catch (QiniuException e2) {
			//新建一个OperationManager对象
			  OperationManager operater = new OperationManager(auth,c);
			  //设置要转码的空间和key，并且这个key在你空间中存在
			  //设置转码操作参数
			  String fops = "avthumb/mp3/ab/160k/ar/44100/acodec/libmp3lame";
			  //设置转码的队列
			  String pipeline = "amr-mp3";
			  //可以对转码后的文件进行使用saveas参数自定义命名，当然也可以不指定文件会默认命名并保存在当前空间。
			  String urlbase64 = UrlSafeBase64.encodeToString(bucketName+":"+mp3);
			  String pfops = fops + "|saveas/"+urlbase64;
			  //设置pipeline参数
			  StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", pipeline);
			  try {
			    String persistid = operater.pfop(bucketName, key, pfops, params);
			    //打印返回的persistid
			    System.out.println(persistid);
			  } catch (QiniuException e) {
			    //捕获异常信息
			      Response r = e.response;
			      // 请求失败时简单状态信息
			      System.out.println(r.toString());
			      try {
			         // 响应的文本信息
			        System.out.println(r.bodyString());
			      } catch (QiniuException e1) {
			          //ignore
			      }
			  }
		  }
		  
	}
	

    
	private BucketManager getBucketManager() {
        return new BucketManager(auth, c);
    }
	// 把远程url，导入到七牛
    public boolean uploadFileWithUrl(String resid, String url)
    {
        if (null != resid && null != url) {
            BucketManager bm = getBucketManager();

            try {
                FetchRet response = bm.fetch(url, bucketName, resid);
                //解析上传成功的结果
                return null != response.key;
            } catch (QiniuException ex) {
                return ex.code() == 579;        // 上传七牛成功，回调失败，这里不需要回调
            }

        }
        return false;
    }
	
	public static void main(String[] args) throws Exception {
		System.out.println(new Pic2Util().uploadFileWithUrl("shihou_4197b84fb847da7018720abcd2b2bc22.jpg","http://peidengku.com//Documents/image/4197b84fb847da7018720abcd2b2bc22.JPG"));
		// http://7vijhu.com1.z0.glb.clouddn.com/
		//System.out.println(new BucketManager(auth, c).stat(bucketName, "mr.wav"));
		
//		"D:\\weiin\\1.mp3"
		// new PicUtil().upload("D:\\桌面备份\\新建文本文档.txt", "helloworld.txt");
		// System.out.print(PicUtil.getUptoken());
		/*
		 * String paramsStr = new String(new
		 * sun.misc.BASE64Decoder().decodeBuffer(
		 * "eydrZXknOiJkYXRhL3Bob3RvL3VzZXIvMTU2NTE4OTUwMjUvaGVhZFBob3RvIiwnd2lkdGgnOicyOTMnLCdoZWlnaHQnOicyOTInLCd6aGlmdWJhbyc6IiIsJ2ZpbmFuY2lhbEFjY291bnQnOiIiLCdmaW5hbmNpYWxBY2NvdW50SW5mbyc6IiIsJ25pY2tuYW1lJzoi5ri45rOz55qE6bG8IiwnZW1haWwnOiIxIiwncGFzc3dvcmQnOiIifQ=="
		 * .replace("-", "+")), "utf-8"); toMap(paramsStr);
		 * 
		 * System.out.print(paramsStr);
		 */
	}

	public static String getUptoken() {
		return auth.uploadToken(bucketName);
	}

	public void upload(String local, String key) throws IOException {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(local, key, Pic2Util.getUptoken());
			// 打印返回的信息
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				// 响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
		}
	}

}
